package com.iye.puretennis.activity;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import com.iye.puretennis.LoginActivity;
import com.iye.puretennis.R;
import com.iye.puretennis.custom.ExitApplication;
import com.iye.puretennis.custom.LocationHandler;
import com.iye.puretennis.domain.CacheType;
import com.iye.puretennis.domain.UrlSuffix;
import com.iye.puretennis.domain.UserToken;
import com.iye.puretennis.fragment.AvailableFragment;
import com.iye.puretennis.fragment.MyAppointmentsFragment;
import com.iye.puretennis.fragment.MyGroupsFragment;
import com.iye.puretennis.fragment.UserDetailFragment;
import com.iye.puretennis.helper.*;
import com.iye.puretennis.utils.StringUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Set;

/**
 * Author: Chuanbao on 2014/11/21.
 */
public class MainTabsActivity extends TabsIndicatorActivity {
    public static final int FRAGMENT_ONE = 0;
    public static final int FRAGMENT_TWO = 1;
    public static final int FRAGMENT_THREE = 2;
    public static final int FRAGMENT_FOUR = 3;

    private DBManager dbManager;

    private UserToken userToken;

    private String registrationID;

    private LocationHandler locationHandler;


    protected DisplayImageOptions.Builder builder;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        ExitApplication.getInstance().addActivity(this);

        dbManager = new DBManager(this);


        locationHandler = new LocationHandler(this, dbManager);
        locationHandler.stopGPS();
        userToken = dbManager.retrieveCurrentUser();

        if (userToken == null) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        } else {

            String token = userToken.getToken();

            builder = ImageHelper.createImageBuilder();

            final String userDevice = CacheType.USER_DEVICE.name();

            registrationID = dbManager.retrieveMyCachedData(userDevice);

            if (!StringUtils.hasText(registrationID)) {

                registrationID = JPushInterface.getRegistrationID(getApplicationContext());

                dbManager.cacheMyData(userDevice, registrationID);
            }

            locationHandler.updateLocation(token);
            String cacheType = CacheType.USER_ALIAS.name();
            String cachedData = dbManager.retrieveMyCachedData(cacheType);
            if (!StringUtils.hasText(cachedData)) {
                addUserDevice();
            }
        }


    }


    @Override
    protected int supplyTabs(List<TabsIndicatorActivity.TabInfo> tabs) {
        tabs.add(new TabsIndicatorActivity.TabInfo(FRAGMENT_ONE, getString(R.string.group), R.drawable.tab_groups,
                MyGroupsFragment.class));
        tabs.add(new TabsIndicatorActivity.TabInfo(FRAGMENT_TWO, getString(R.string.appointment), R.drawable.tab_appointment,
                MyAppointmentsFragment.class));
        tabs.add(new TabsIndicatorActivity.TabInfo(FRAGMENT_THREE, getString(R.string.time), R.drawable.tab_time,
                AvailableFragment.class));
        tabs.add(new TabsIndicatorActivity.TabInfo(FRAGMENT_FOUR, getString(R.string.me), R.drawable.tab_me,
                UserDetailFragment.class));

        return FRAGMENT_ONE;
    }

    //log out the system
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            exitApp();
            return true;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }

    private long exitTime = 0;

    public void exitApp() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(this, getString(R.string.exit_system), Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            if (hasNetWork()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (ServerAccessHelper.logout(userToken.getToken(), registrationID)) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    doExitApp();
                                }
                            });
                        }
                    }
                }).start();

            } else {
                doExitApp();
            }
        }
    }

    private void doExitApp() {
//        dbManager.logout();
        ExitApplication.getInstance().exit();
    }

    public void logout() {
        if (hasNetWork()) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    if (ServerAccessHelper.logout(userToken.getToken(), registrationID)) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                doLogout();
                            }
                        });
                    }
                }
            }

            ).start();
        } else {
            doLogout();
        }
    }

    private void doLogout() {
        locationHandler.stopGPS();
        dbManager.logout();
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

    private boolean hasNetWork() {
        ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        cwjManager.getActiveNetworkInfo();

        return cwjManager.getActiveNetworkInfo() != null && cwjManager.getActiveNetworkInfo().isAvailable();

    }

    private void addUserDevice() {

        final String uuid = UUIDGenerator.createUUID();

        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, uuid));

    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, final String alias, Set<String> tags) {
            switch (code) {
                case 0:
                    final String finalRegistrationID = registrationID;
                    new Thread(new Runnable() {
                        JSONObject paramJson = new JSONObject();

                        @Override
                        public void run() {
                            try {
                                paramJson.put("type", "android");
                                paramJson.put("alias", alias);
                                paramJson.put("registrationID", finalRegistrationID);
                                StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);
                                String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.ADD_DEVICE), userToken.getToken(), paramEntity);
                                if (!Constant.RESPONSE_BADLY.equals(result)) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            dbManager.cacheMyData(CacheType.USER_ALIAS.name(), alias);
                                        }
                                    });
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    break;
                case 6002:
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 10);
                    break;
                default:
                    String logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }
        }
    };

    private static final int MSG_SET_ALIAS = 1001;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };

    @Override
    protected void onResume() {

        super.onResume();

        JPushInterface.onResume(this);

    }

    @Override
    protected void onPause() {

        super.onPause();

        JPushInterface.onPause(this);

    }

    public DisplayImageOptions.Builder getBuilder() {
        return builder;
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v != null && isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


}